﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api;
using System.Text;
using System.Runtime.InteropServices;
using IWshRuntimeLibrary;
using System.Data;
using DBControl;
using System.Security.Cryptography; 

namespace ZSZK
{
    public partial class subindex : System.Web.UI.Page
    {
        private static string appkey = System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString();
        private static string appsecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
        private static string appurl = System.Configuration.ConfigurationManager.AppSettings["AppUrl"].ToString();
        private static ITopClient client = new DefaultTopClient(appurl, appkey, appsecret);

        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["ParentusNick"] == null || Session["ParentsessionKey"] == null || Session["subUserNick"] == null || Session["subid"] == null)
                {
                    Response.Redirect("404.htm");
                    return;
                }
                else
                {
                    setSubmaxmoney();
                    GetTreelist(Session["ParentusNick"].ToString());
                    Getgoodlist(null);
                    bindchatter(Session["subUserNick"].ToString());
                }
            }
        }

        /// <summary>
        /// 获取当前会话用户店铺的自定义列表
        /// </summary>
        /// <param name="usNick">当前会话用户昵称</param>
        /// <returns></returns>
        private void GetTreelist(string usNick)
        {
            SellercatsListGetRequest scListreq = new SellercatsListGetRequest();
            scListreq.Nick = usNick;
            scListreq.Fields = "cid,name,parent_cid,sort_order";
            SellercatsListGetResponse scListgetRes = client.Execute(scListreq);
            List<SellerCat> sclistParent = scListgetRes.SellerCats.FindAll(delegate(SellerCat scat) { return scat.ParentCid == 0; });
            List<SellerCat> sclistChildren = scListgetRes.SellerCats.FindAll(delegate(SellerCat scat) { return scat.ParentCid != 0; });

            TreeNode mtn = new TreeNode("所有宝贝", "all");
            this.cateTree.Nodes.Add(mtn);
            foreach (var item in sclistParent)
            {
                TreeNode tn = new TreeNode(item.Name, item.Cid.ToString());
                mtn.ChildNodes.Add(tn);
                foreach (var itemchild in sclistChildren)
                {
                    if (itemchild.ParentCid == item.Cid)
                    {
                        TreeNode tnchild = new TreeNode(itemchild.Name, itemchild.Cid.ToString());
                        tn.ChildNodes.Add(tnchild);
                    }
                }
            }
        }

        private void Getgoodlist(string cid, long pageno = 1)
        {
            ItemsOnsaleGetRequest onsellreq = new ItemsOnsaleGetRequest();
            onsellreq.Fields = "num_iid,title,price,pic_url";
            onsellreq.PageSize = this.AspNetPager.PageSize;
            onsellreq.PageNo = pageno;
            if (cid != null)
            {
                onsellreq.SellerCids = cid;
            }
            ItemsOnsaleGetResponse onSellRes = client.Execute(onsellreq, Session["ParentsessionKey"].ToString());
            this.goodlist.DataSource = onSellRes.Items;
            this.goodlist.DataBind();
            this.AspNetPager.RecordCount = int.Parse(onSellRes.TotalResults.ToString());
        }


        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            if (ViewState["searchkeyword"] != null)
            {
                bindsearch(this.AspNetPager.CurrentPageIndex);
            }
            else
            {
                Getgoodlist(this.cateTree.SelectedValue, this.AspNetPager.CurrentPageIndex);
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        protected void cateTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            ViewState.Clear();

            if (this.cateTree.SelectedValue == "all")
            {
                Getgoodlist(null);
            }
            else
            {
                Getgoodlist(this.cateTree.SelectedValue);
            }
            this.AspNetPager.CurrentPageIndex = 1;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        private void bindchatter(string usNick)
        {
            WangwangEserviceChatpeersGetRequest req = new WangwangEserviceChatpeersGetRequest();
            req.ChatId = "cntaobao" + usNick;
            req.StartDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
            req.EndDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
            WangwangEserviceChatpeersGetResponse response = client.Execute(req, Session["ParentsessionKey"].ToString());
            if (!response.IsError)
            {
                var pn = (from m in response.Chatpeers
                          orderby m.Date descending
                          select m).Take(10).ToList<Chatpeer>();
                ListItem nli = new ListItem("");
                this.chatter.Items.Add(nli);
                foreach (var item in pn)
                {
                    ListItem li = new ListItem(item.Uid.Replace("cntaobao", ""));
                    this.chatter.Items.Add(li);
                }
            }
            else
            {
            }
        }

        protected void deltag_Click(object sender, EventArgs e)
        {

        }

        protected void search_Click(object sender, EventArgs e)
        {
            if (this.keyword.Text == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alerterror", "<script>alert('请输入查询宝贝的标题!')</script>", false);
            }
            else
            {
                if (this.cateTree.SelectedNode != null)
                {
                    this.cateTree.SelectedNode.Selected = false;
                }
                ViewState.Add("searchkeyword", this.keyword.Text.Trim());
                bindsearch();
                this.AspNetPager.CurrentPageIndex = 1;
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "resizeImg", "<script>resizeImg()</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onloadfun", "<script>onloadfun();</script>", false);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "opendialog", "<script>opendialog();</script>", false);
        }

        private void bindsearch(long pageno = 1)
        {
            ItemsGetRequest itemsreq = new ItemsGetRequest();
            itemsreq.Fields = "num_iid,title,price,pic_url";
            itemsreq.Q = ViewState["searchkeyword"].ToString();
            itemsreq.PageSize = this.AspNetPager.PageSize;
            itemsreq.Nicks = Session["ParentusNick"].ToString();
            itemsreq.PageNo = pageno;
            ItemsGetResponse itemsrep = client.Execute(itemsreq);
            this.goodlist.DataSource = itemsrep.Items;
            this.goodlist.DataBind();
            this.AspNetPager.RecordCount = int.Parse(itemsrep.TotalResults.ToString());
        }

        private void setSubmaxmoney()
        {
            string getsubmax = "SELECT maxmoney FROM UserSession WHERE UsID = '" + Session["subid"] + "'";
            SqlDbHelper sdh = new SqlDbHelper();
            this.submaxmoney.Value = sdh.ExecuteScalar(getsubmax).ToString();
        }
    }
}